package lv.solcraft.replication.client.rest;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.apache.log4j.Logger;
import org.restlet.Filter;
import org.restlet.data.CharacterSet;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.StringRepresentation;

public class ErrorFilter extends Filter {

    private static final Logger log = Logger.getLogger(ErrorFilter.class);

    @Override
    protected int doHandle(Request request, Response response) {
        try {
            return super.doHandle(request, response);
        } catch (Throwable e) {
            log.error("Request handling failed", e);
            response.setStatus(Status.SERVER_ERROR_INTERNAL);
            StringRepresentation repr = createErrorMessage(e);
            response.setEntity(repr);
            return STOP;
        }
    }

    private StringRepresentation createErrorMessage(final Throwable error) {
        StringBuilder sb = new StringBuilder();
        sb.append("\nERROR MESSAGES:\n");
        {
            Throwable e = error;
            while (e != null) {
                sb.append(e.getMessage()).append("\n");
                e = e.getCause();
            }
        }
        sb.append("\nSTACK TRACE:\n");
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        error.printStackTrace(pw);
        sb.append(sw.toString());
        String message = sb.toString();
        return new StringRepresentation(message, MediaType.ALL, Language.ALL, CharacterSet.UTF_8);
    }
}
